package com.chenye.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Auther:chenye
 * @Data:2018/8/23
 * @Description:
 */
public class JdkProxy implements InvocationHandler {
    private Object target;

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.err.println("执行了代理方法");
        Object result = method.invoke(target,args);//如果是直接代理空接口那么这里不能调用invoke方法，需要实现自己的处理逻辑
        return result;
    }

    public static void main(String args[]){
        JdkProxy jdkProxy = new JdkProxy();
        jdkProxy.setTarget(new Person());//jdk动态代理不仅仅可以代理实现了接口的类，还能直接代理空接口
        //这里只能转成接口对象,相当于生成了一个新的person1对象
        Human human = (Human)Proxy.newProxyInstance(jdkProxy.getClass().getClassLoader(),new Class[]{Human.class},jdkProxy);
        System.err.println(human.say("chenye"));

        try {
            Class human1 = Class.forName("com.chenye.proxy.Human");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
